package core.java;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Arrays;
import java.util.Iterator;

/**
 * @Author SSK
 * @Date Created in 20:54 2019/8/23
 * @Description TODO
 * @Version 1.0
 */
public class NoiServer {
    final public int PORT;
    private boolean run;
    private ServerSocketChannel serverSocketChannel;
    public NoiServer(int port) {
        this.PORT = port;
        run = false;
    }
    public void start() throws IOException {
        run = true;
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(8000));
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (run&&selector.isOpen()) {
            int result = selector.select();
            if (result == 0) {
                continue;
            }
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                SelectableChannel selectableChannel = selectionKey.channel();
                if (selectionKey.isValid() && selectionKey.isAcceptable()) {
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectableChannel;
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(100));
                } else if (selectionKey.isValid() && selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) selectableChannel;
                    ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                    int len = socketChannel.read(byteBuffer);
                    String s = new String(Arrays.copyOfRange(byteBuffer.array(), 0, byteBuffer.position()),"utf-8");
                    if (len == -1 || s.indexOf("exit") != -1) {
                        socketChannel.close();
                        continue;
                    }
                    int endIndex = s.indexOf("endl");
                    if (endIndex != -1) {
                        s = s.substring(0, endIndex);
                        byteBuffer.limit(s.getBytes("utf-8").length);
                    }
                    System.out.println(s + " " + byteBuffer);
                    byteBuffer.flip();
                    socketChannel.write(byteBuffer);
                    if (endIndex != -1) {
                        byteBuffer.clear();
                        byteBuffer.put("endl".getBytes("utf-8"));
                        byteBuffer.flip();
                        socketChannel.write(byteBuffer);
                        byteBuffer.clear();
                    } else
                        byteBuffer.compact();
                }


            }
            iterator.remove();

        }

        serverSocketChannel.close();
    }
    public void stop(){
        run = false;
    }
    public static void main ( String[] args)  {
        try {
            NoiServer noiServer = new NoiServer(8000);
            noiServer.start();
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}

